今天來練習模擬滑鼠點擊的測試寫法:
情境:畫面上一個按鈕,點擊顯示+1數字於畫面上。
import { useState } from "react"
export default function Counter(){
const [ counter, setCounter ] = useState(0);
return(
<>
<h1>{counter}</h1>
<button onClick={() => setCounter(pre => pre+1)}>Add 1</button>
</>
)
}
第一步測試:確認畫面上有 <h1>
<button>
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./counter";
describe("Counter", () => {
// (1) 檢查是否有正確顯示在畫面上,與初始值
test("Render correctly!", () => {
render(<Counter />);
const counterEl = screen.getByRole("heading", {
level: 1
});
expect(counterEl).toHaveTextContent("0"); // 記得要輸入的是字串型別
const btnEl = screen.getByRole("button", {
name: "Add 1"
});
expect(btnEl).toBeInTheDocument();
});
});
測試結果:
PASS src/components/counter/counter.test.tsx
第二步測試:模擬使用者點擊按鈕,畫面會出現 +1 數字。
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./counter";
describe("Counter", () => {
(2) 模擬使用者點擊按鈕,數字加一的效果
test("Show the counter of 1 after clicking the button!", async() => {
render(<Counter />);
const btnEl = screen.getByRole("button", {
name: "Add 1"
});
await userEvent.click(btnEl);
const counterEl = screen.getByRole("heading", {
level: 1
});
expect(counterEl).toHaveTextContent("1"); // 記得要輸入的是字串型別
});
});
測試結果:
PASS src/components/counter/counter.test.ts